<?php
namespace frontend\models;
use yii\base\Model;
use Yii;
use common\models\PostsModel;
use frontend\models\TagForm;
use common\models\RelationPostTagsModel;
use yii\db\Query;

class PostForm extends \yii\base\Model{
    public $id;
    public $title;
    public $summary;
    public $content;
    public $label_img;
    public $user_id;
    public $user_name;
    public $cat_id;
    public $tags;
    public $_lastError="";
    
    //创建场景
    const SCENARIO_CREATE='create';
    const SCENARIO_UPDATE='update';

    //定义事件
    const EVENT_AFTER_CREATE='eventAfterCreate';//创建的事件
    const EVENT_AFTER_UPDATE='eventAfterUpdate';

    public function scenarios() {
        $scenarios=[
        self::SCENARIO_CREATE=>['title','content','label_img','tags'],
        self::SCENARIO_UPDATE=>['title','content','label_img','tags'],
        ];
        return array_merge(parent::scenarios(),$scenarios);
    }

    public function rules(){
        return [
            [['id','title','content','cat_id'],'required'],
            [['id','cat_id'],'integer'],
            ['title','string','min'=>4,'max'=>50],
        ];
    }
    
    public function attributeLabels() {
        return [
            'id'=>'编码',
            'title'=>'标题',
            'content'=>'内容',
            'label_img'=>'标签图',
            'tags'=>'标签',
            'cat_id'=>'分类id'
        ];
    }
    //文章创建
    public function create(){
        //事务
        $transaction= Yii::$app->db->beginTransaction();
        try {
            $model=new PostsModel();
            $model->setAttributes($this->attributes);
            
            $model->summary= $this->_getSummary();
            $model->user_id= Yii::$app->user->identity->id;
            $model->user_name= Yii::$app->user->identity->username;
            $model->is_valid= \common\models\PostsModel::IS_VALID;
            $model->created_at= time();
            $model->updated_at= time();
            if(!$model->save()){
                throw new Exception('文字保存失败');
            }
            $this->id=$model->id;
            //调用事件
            $data= array_merge($this->getAttributes(),$model->getAttributes());
//            $this->_eventAfterCreate($data);
            
            $transaction->commit();
            return true;
        } catch (\Exception $exc) {
           
            $transaction->rollBack();//出错回滚
            $this->_lastError=$exc->getMessage();//记载错误
            return false;
        }
        }
        
    //获取文章根据id
    public function getViewById($id){
        $res=PostsModel::find()->with('relate.tag','extend')->where(['id'=>$id])->asArray()->one();
        if(!$res){
            throw new \yii\web\NotFoundHttpException('文章不存在');
        }
//        print_r($res);exit;
        $res['tags']=[];
        if(isset($res['relate']) && !empty($res['relate'])){
            foreach ($res['relate'] as $list) {
                $res['tags'][]=$list['tag']['tag_name'];
            }
        }
        unset($res['relate']);
//        print_r($res); exit();
        return $res;
    }


    //截取文章摘要
    private function _getSummary($s=0,$e=90,$char="utf-8"){
            if(empty($this->content))
                return null;
            return (mb_substr(str_replace('&nbsp;', '', strip_tags($this->content)),$s,$e, $char));
        }
        
    //创建完成后调用的事件方法
    public function _eventAfterCreate($data)
    {
        //添加事件
        $this->on(self::EVENT_AFTER_CREATE, [$this,'_eventAddTag'],$data);    
        //触发事件
        $this->trigger(self::EVENT_AFTER_CREATE);
    }
    
    //添加标签
    public function _eventAddTag($event){
        //保存标签
        $tag=new TagForm();
        $tag->tags=$event->data['tags'];
        $tagids=$tag->saveTags();
        
        //删除原先的关联关系
        RelationPostTagsModel::deleteAll(['post_id'=>$event->data['id']]);
        var_dump($tagids);exit;
        //批量保存
        if(!empty($tagids)){
            foreach ($tagids as $k => $id) {
                $row[$k]['post_id']= $this->id;
                $row[$k]['tag_id']= $id;
            }
            $res=(new Query())->createCommand()
                    ->batchInsert(RelationPostTagsModel::tableName(), ['post_id','tag_id'],$row)
                    ->execute();
            if(!$res){
                throw new Exception('关联关系保存失败！');
            }
        }
    }
    
    public static function getList($cond,$curPage=1, $pageSize=5,$orderBy=['id'=>SORT_DESC]){
        $model=new PostsModel();
        $select=['id','title','summary','content','label_img','cat_id','user_id','user_name',
            'is_valid','created_at','updated_at'];
        $query=$model->find()->select($select)
                ->where($cond)->with('relate.tag','extend')
                ->orderBy($orderBy);
        //获取分页数据
        $res=$model->getPages($query,$curPage,$pageSize);
        //格式化
        $res['data']= self::_formatList($res['data']);
        return $res;
    }
    
    //数据格式化
    public static function _formatList($data){
        foreach ($data as &$list){
            $list['tags']=[];
            if(isset($list['relate']) && !empty($list['relate'])){
                foreach ($list['relate'] as $lt) {
                    $list['tags'][]=$lt['tag']['tag_name'];
                }
            }
             unset($list['relate']);
        }
       
        return $data;
    }
    
}

